import 'package:common_utils/common_utils.dart';
import 'package:fate_blind_box/model/box_open_list_entity.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/network/http_request.dart';
import 'package:fate_blind_box/ui/pay/change_pay.dart';
import 'package:fate_blind_box/ui/pay/payout.dart';
import 'package:fate_blind_box/ui/user/Invite4.dart';
import 'package:fate_blind_box/ui/user/profile.dart';
import 'package:fate_blind_box/utils/bottom_sheet.dart';
import 'package:fate_blind_box/utils/default/common_config.dart';
import 'package:fate_blind_box/utils/default/over_lay_filter_view.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/page.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_quill_extensions/shims/dart_ui_real.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'state.dart';

class MeetBlindBoxLogic extends GetxController {
  final MeetBlindBoxState state = MeetBlindBoxState();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    getData();
    aaaa();
  }

  /// 推荐(左滑惊喜)
  getData() async {
    // 清空数组
    state.blindList.clear();
    state.isOpenSign.clear();
    // 查看盲盒列表
    final blindRes = await Api.getInstance().blindList();
    if (blindRes['data'] != null) {
      blindRes['data'].forEach((v) {
        state.blindList.add(BoxOpenListEntity.fromJson(v));
        state.isOpenSign.add({"isOpenSign": 0});
      });
      state.isOpenSign.refresh();
      state.blindList.refresh();
    } else {
      //空的话，调用已经看过的接口
      _getMeLookListLeft(1);
    }
    // 查看 盲盒剩余次数
    final countRes = await Api.getInstance().blindChance();
    state.totalCount.value = countRes['data']?['total'] ?? 0;
  }

  /// 添加蒙版
  aaaa(){
    if (CommonConfig.isShowGuide == false) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        OverLayFilerView.showView(Get.context!);
        CommonConfig.isShowGuide = true;
      });
    }
    Future.delayed(const Duration(seconds: 5)).then((value) {
      OverLayFilerView.dismiss();
    });
  }

  ///左滑查看-我看过的列表
  _getMeLookListLeft(int page) async {
    final res = await Api.getInstance().getMeLook(Provider.memberId);
    if (res['data'] != null) {
      state.blindList.clear();
      state.isOpenSign.clear();
      res['data'].forEach((v) {
        state.isSeedRight = true;
        state.blindList.add(BoxOpenListEntity.fromJson(v));
        state.isOpenSign.add({"isOpenSign": 0});
      });
      state.isOpenSign.refresh();
      state.blindList.refresh();
    } else {
      //还没有看过的，不做处理
    }
  }

  ///第一次右滑，还没有看过的数据，加载左滑数据
  _getRightData() async {
    final blindRes = await Api.getInstance().blindList();
    final countRes = await Api.getInstance().blindChance();
    state.totalCount = countRes['data']?['total'] ?? 0;
    List blindData = blindRes['data'];
    if (blindData.isNotEmpty) {
      state.listData.clear();
      state.listData == [];
      state.listData.add(blindData[0]);
      state.isOpenSign.clear();
      state.isOpenSign == [];
      // for(var item in _listData) {
      state.isOpenSign.add({"isOpenSign": 0});
      // }
      state.tCardController.reset();
    }
  }

  blindOpen(String id) async {
    if (state.totalCount < 1) {
      final res =
          await BottomSheetDialog.show(Get.context!, const PayoutWidget());
      if (res == 1) {
        Navigate.toPage(const Invite4Ui());
      } else if (res == 2) {
        final res = await Navigate.toPage(const Pay4ChangeUi());
        if (res != null && res is int && res > 0) {
          state.totalCount.value += res;
        }
      }
    } else {
      final res = await Api.getInstance().blindOpen(id);
      if (res["code"] == 0) {
        state.totalCount.value--;
        state.isOpenSign[0]['isOpenSign'] = 1;
        await Future.delayed(const Duration(milliseconds: 500));
        state.tCardController.reset();
        Navigator.push(Get.context!, CupertinoPageRoute(builder: (context){
          return UserProfileUi(memberId: id);
        }));
      } else {
        toast(res['msg']);
      }
    }
  }

  ///我看过的
  getMeLookList(int page) async {
    final res = await Api.getInstance().getMeLook(Provider.memberId);
    state.seedData = res['data'];
    if (state.seedData.isNotEmpty) {
      state.isSeedRight = true;
      // isRight = false;
      //有看过的
      List list = state.seedData;
      if (list.isNotEmpty) {
        state.listData.clear();
        state.listData.addAll(list);
        state.listData.refresh();
      }
      LogUtil.e('cccc ${state.listData.length}');
      state.tCardController.reset();
    } else {
      //还没有看过的，加载未看过的数据（也就是左滑数据）
      _getRightData();
    }
  }

  /// 检查类型
  Widget checkType(dynamic type) {
    double filterValue = CommonConfig.isShowPay() == false ? 0.0 : 6.0;
    if (type == 1) {
      return const SizedBox(
        width: 0,
        height: 0,
      );
    } else if (type == 0) {
      return BackdropFilter(
        filter: ImageFilter.blur(sigmaX: filterValue, sigmaY: filterValue),
        child: Container(
            // height: 250,
            // width: 225,
            height: 355.w,
            width: 296.w,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.0),
            )),
      );
    }
    return Container();
  }

  /// 打开付款界面
  jumpPayView() async {
    jumpShowPayView();
  }

  /// 跳转页面
  void jumpShowPayView() async {
    final res =
        await BottomSheetDialog.show(Get.context!, const PayoutWidget());
    if (res == 1) {
      Navigate.toPage(const Invite4Ui());
    } else if (res == 2) {
      final res = await Navigate.toPage(const Pay4ChangeUi());
      LogUtil.e(res);
      if (res != null && res is int && res > 0) {
        state.totalCount.value += res;
      }
    }
  }

  /// 获取最新的匹配数据
  getLatestMatchData(String codeStr) async {
    var res = await HttpRequest.request(
      'match-maker/business/scanWhoIShere',
      params: {"shareCode": codeStr},
    );
    if (res != null && res['code'] == 0) {
      if (res['data'] != null) {
        List dataList = res['data'];
        if (state.isRight == true) {
          state.blindList.removeAt(0);
          state.isOpenSign.removeAt(0);
          state.isRight = false;
        }
        if (dataList.isNotEmpty) {
          state.blindList.clear();
          res['data'].forEach((v) {
            state.blindList.add(BoxOpenListEntity.fromJson(v));
            state.isOpenSign.add({"isOpenSign": 0});
          });
          state.blindList.refresh();
          state.isOpenSign.refresh();
          state.tCardController.reset();
        } else {
          //空的话，调用已经看过的接口
          _getMeLookListLeft(1);
        }
      }
    }
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    state.tCardController.dispose();
  }
}
